#include "TcpServer.h"
#include "RobotClient.h"
#include "DisconnectLogger.h"

TcpServer::TcpServer(QObject *parent)
    : QObject(parent), m_server(new QTcpServer(this))
{
    connect(m_server, &QTcpServer::newConnection, this, &TcpServer::onNewConnection);
}

TcpServer::~TcpServer()
{
    stopServer();
}

bool TcpServer::startServer(int port)
{
    if (m_server->isListening()) {
        qDebug() << "TCP服务器已在运行";
        return true;
    }

    if (!m_server->listen(QHostAddress::Any, port)) {
        QString errorMsg = QString("TCP服务器启动失败: %1").arg(m_server->errorString());
        qDebug() << errorMsg;
        emit serverError(errorMsg);
        return false;
    }

    QString address = getLocalIPAddress();
    qDebug() << QString("TCP服务器已启动，监听地址: %1:%2").arg(address).arg(port);
    emit serverStarted(address, port);
    return true;
}

void TcpServer::stopServer()
{
    if (!m_server->isListening()) {
        return;
    }

    // 断开所有客户端连接
    for (RobotClient *client : m_clients) {
        client->disconnectFromHost();
        client->deleteLater();
    }
    m_clients.clear();

    m_server->close();
    qDebug() << "TCP服务器已停止";
    emit serverStopped();
}

bool TcpServer::isRunning() const
{
    return m_server->isListening();
}

QString TcpServer::getServerAddress() const
{
    if (m_server->isListening()) {
        // 优先获取WLAN网卡的IP地址
        QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
        
        // 第一轮：优先查找WLAN相关网卡
        for (const QNetworkInterface &interface : interfaces) {
            if (interface.flags() & QNetworkInterface::IsUp &&
                interface.flags() & QNetworkInterface::IsRunning &&
                !(interface.flags() & QNetworkInterface::IsLoopBack)) {
                
                QString interfaceName = interface.name().toLower();
                // 检查是否是WLAN网卡（常见的WLAN网卡名称）
                if (interfaceName.contains("wlan") || 
                    interfaceName.contains("wifi") ||
                    interfaceName.contains("wireless") ||
                    interfaceName.startsWith("wl")) {
                    
                    QList<QNetworkAddressEntry> entries = interface.addressEntries();
                    for (const QNetworkAddressEntry &entry : entries) {
                        QHostAddress address = entry.ip();
                        if (address.protocol() == QAbstractSocket::IPv4Protocol &&
                            !address.isLoopback() &&
                            !address.toString().startsWith("169.254")) {
                            qDebug() << "使用WLAN网卡地址:" << address.toString() << "(" << interface.name() << ")";
                            return address.toString();
                        }
                    }
                }
            }
        }
        
        // 第二轮：查找以太网网卡
        for (const QNetworkInterface &interface : interfaces) {
            if (interface.flags() & QNetworkInterface::IsUp &&
                interface.flags() & QNetworkInterface::IsRunning &&
                !(interface.flags() & QNetworkInterface::IsLoopBack)) {
                
                QString interfaceName = interface.name().toLower();
                // 检查是否是以太网网卡
                if (interfaceName.contains("ethernet") ||
                    interfaceName.contains("eth") ||
                    interfaceName.startsWith("en")) {
                    
                    QList<QNetworkAddressEntry> entries = interface.addressEntries();
                    for (const QNetworkAddressEntry &entry : entries) {
                        QHostAddress address = entry.ip();
                        if (address.protocol() == QAbstractSocket::IPv4Protocol &&
                            !address.isLoopback() &&
                            !address.toString().startsWith("169.254")) {
                            qDebug() << "使用以太网网卡地址:" << address.toString() << "(" << interface.name() << ")";
                            return address.toString();
                        }
                    }
                }
            }
        }
        
        // 第三轮：排除常见虚拟网卡后的其他网卡
        for (const QNetworkInterface &interface : interfaces) {
            if (interface.flags() & QNetworkInterface::IsUp &&
                interface.flags() & QNetworkInterface::IsRunning &&
                !(interface.flags() & QNetworkInterface::IsLoopBack)) {
                
                QString interfaceName = interface.name().toLower();
                // 排除常见的虚拟网卡
                if (!interfaceName.contains("vmware") &&
                    !interfaceName.contains("virtualbox") &&
                    !interfaceName.contains("vbox") &&
                    !interfaceName.contains("hyper-v") &&
                    !interfaceName.contains("docker") &&
                    !interfaceName.contains("bridge") &&
                    !interfaceName.contains("tap") &&
                    !interfaceName.contains("tun") &&
                    !interfaceName.contains("loopback") &&
                    !interfaceName.contains("teredo") &&
                    !interfaceName.contains("isatap")) {
                    
                    QList<QNetworkAddressEntry> entries = interface.addressEntries();
                    for (const QNetworkAddressEntry &entry : entries) {
                        QHostAddress address = entry.ip();
                        if (address.protocol() == QAbstractSocket::IPv4Protocol &&
                            !address.isLoopback() &&
                            !address.toString().startsWith("169.254")) {
                            qDebug() << "使用网卡地址:" << address.toString() << "(" << interface.name() << ")";
                            return address.toString();
                        }
                    }
                }
            }
        }
        
        qDebug() << "未找到合适的网卡，使用回环地址";
        return "127.0.0.1";
    }
    return QString();
}

int TcpServer::getServerPort() const
{
    if (m_server->isListening()) {
        return m_server->serverPort();
    }
    return -1;
}

int TcpServer::getConnectedClientsCount() const
{
    return m_clients.size();
}

RobotClient* TcpServer::findClientBySN(const QString &sn) const
{
    for (RobotClient *client : m_clients) {
        if (client->getRobotSN() == sn) {
            return client;
        }
    }
    return nullptr;
}

QList<RobotClient*> TcpServer::getAllClients() const
{
    return m_clients;
}

bool TcpServer::disconnectRobotBySN(const QString &sn)
{
    RobotClient *client = findClientBySN(sn);
    if (client) {
        QString clientAddress = client->getClientAddress();
        QString clientSN = client->getRobotSN();
        
        // 记录手动断开连接日志
        DisconnectLogger::instance()->logManualDisconnect(
            sn,
            clientAddress,
            QString("服务端手动断开机器人连接"),
            0
        );
        
        qDebug() << QString("主动断开机器人连接: %1").arg(sn);
        client->disconnectFromHost();
        return true;
    }
    
    // 记录未找到机器人的日志
    DisconnectLogger::instance()->logManualDisconnect(
        sn,
        "",
        QString("未找到指定SN的机器人客户端"),
        0
    );
    
    return false;
}

void TcpServer::onNewConnection()
{
    while (m_server->hasPendingConnections()) {
        QTcpSocket *socket = m_server->nextPendingConnection();
        
        if (socket) {
            QString clientAddress = socket->peerAddress().toString();
            int clientPort = socket->peerPort();
            
            qDebug() << QString("新客户端连接: %1:%2").arg(clientAddress).arg(clientPort);
            
            // 创建机器人客户端管理对象
            RobotClient *client = new RobotClient(socket, this);
            m_clients.append(client);
            
            // 连接信号
            connect(client, &RobotClient::disconnected, this, &TcpServer::onClientDisconnected);
            connect(client, &RobotClient::registered, this, [this](const QString &sn) {
                // 转发机器人注册信号
                emit robotRegistered(sn);
            });
            connect(client, &RobotClient::dataReceived, this, [this](const QString &sn, const QJsonObject &data) {
                // 转发机器人数据信号
                emit robotDataReceived(sn, data);
            });
            connect(client, &RobotClient::heartbeatReceived, this, [this](const QString &sn, const QJsonObject &data) {
                // 【关键优化】转发心跳信号到RobotManager进行内存状态更新
                emit robotHeartbeatReceived(sn, data);
            });
            connect(client, &RobotClient::jsonParseError, this, [this](const QString &clientIp, const QString &rawData, const QString &errorMsg) {
                // 转发JSON解析错误信号
                emit jsonParseError(clientIp, rawData, errorMsg);
            });
            
            emit clientConnected(clientAddress, clientPort);
        }
    }
}

void TcpServer::onClientDisconnected()
{
    RobotClient *client = qobject_cast<RobotClient*>(sender());
    if (client) {
        QString address = client->getClientAddress();
        QString robotSN = client->getRobotSN();
        
        qDebug() << QString("客户端断开连接: %1").arg(address);
        
        // 如果机器人已注册，发出断开连接信号
        if (!robotSN.isEmpty()) {
            qDebug() << QString("机器人 %1 断开连接").arg(robotSN);
            emit robotDisconnected(robotSN);
        }
        
        m_clients.removeOne(client);
        client->deleteLater();
        
        emit clientDisconnected(address);
    }
}

QString TcpServer::getLocalIPAddress() const
{
    // 优先获取WLAN网卡的IP地址
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    
    // 第一轮：优先查找WLAN相关网卡
    for (const QNetworkInterface &interface : interfaces) {
        if (interface.flags() & QNetworkInterface::IsUp &&
            interface.flags() & QNetworkInterface::IsRunning &&
            !(interface.flags() & QNetworkInterface::IsLoopBack)) {
            
            QString interfaceName = interface.name().toLower();
            // 检查是否是WLAN网卡（常见的WLAN网卡名称）
            if (interfaceName.contains("wlan") || 
                interfaceName.contains("wifi") ||
                interfaceName.contains("wireless") ||
                interfaceName.startsWith("wl")) {
                
                QList<QNetworkAddressEntry> entries = interface.addressEntries();
                for (const QNetworkAddressEntry &entry : entries) {
                    QHostAddress address = entry.ip();
                    if (address.protocol() == QAbstractSocket::IPv4Protocol &&
                        !address.isLoopback() &&
                        !address.toString().startsWith("169.254")) {
                        return address.toString();
                    }
                }
            }
        }
    }
    
    // 第二轮：查找以太网网卡
    for (const QNetworkInterface &interface : interfaces) {
        if (interface.flags() & QNetworkInterface::IsUp &&
            interface.flags() & QNetworkInterface::IsRunning &&
            !(interface.flags() & QNetworkInterface::IsLoopBack)) {
            
            QString interfaceName = interface.name().toLower();
            // 检查是否是以太网网卡
            if (interfaceName.contains("ethernet") ||
                interfaceName.contains("eth") ||
                interfaceName.startsWith("en")) {
                
                QList<QNetworkAddressEntry> entries = interface.addressEntries();
                for (const QNetworkAddressEntry &entry : entries) {
                    QHostAddress address = entry.ip();
                    if (address.protocol() == QAbstractSocket::IPv4Protocol &&
                        !address.isLoopback() &&
                        !address.toString().startsWith("169.254")) {
                        return address.toString();
                    }
                }
            }
        }
    }
    
    // 第三轮：排除虚拟网卡后的其他网卡
    for (const QNetworkInterface &interface : interfaces) {
        if (interface.flags() & QNetworkInterface::IsUp &&
            interface.flags() & QNetworkInterface::IsRunning &&
            !(interface.flags() & QNetworkInterface::IsLoopBack)) {
            
            QString interfaceName = interface.name().toLower();
            // 排除常见的虚拟网卡
            if (!interfaceName.contains("vmware") &&
                !interfaceName.contains("virtualbox") &&
                !interfaceName.contains("vbox") &&
                !interfaceName.contains("hyper-v") &&
                !interfaceName.contains("docker") &&
                !interfaceName.contains("bridge") &&
                !interfaceName.contains("tap") &&
                !interfaceName.contains("tun") &&
                !interfaceName.contains("loopback") &&
                !interfaceName.contains("teredo") &&
                !interfaceName.contains("isatap")) {
                
                QList<QNetworkAddressEntry> entries = interface.addressEntries();
                for (const QNetworkAddressEntry &entry : entries) {
                    QHostAddress address = entry.ip();
                    if (address.protocol() == QAbstractSocket::IPv4Protocol &&
                        !address.isLoopback() &&
                        !address.toString().startsWith("169.254")) {
                        return address.toString();
                    }
                }
            }
        }
    }
    
    return "127.0.0.1";
}